package com.shundr.auth.frame.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * 
 * IpUtils
 * 
 * @author larry 2015-4-10 下午5:07:10
 * @version 1.0.0
 *
 */
public class IpUtils {
	private static final String tag = IpUtils.class.getSimpleName();

	/**
	 * 获得WIFI网络下，本地的ip地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getWifiIpAddress(Context context) {
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		if (wifiManager.isWifiEnabled()) {
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			int ipAddress = wifiInfo.getIpAddress();
			return intToIpAddress(ipAddress);
		}
		return null;
	}

	/**
	 * 获得手机的IMEI
	 * 
	 * @param context
	 * @return
	 */
	public static String getIMEI(Context context) {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = telephonyManager.getDeviceId();
		if (deviceId == null) {
			Log.i(tag, "cannot get the imei code");
			deviceId = "null";
		}
		return deviceId;

	}

	/**
	 * 获得非WIFI网络下，本地的ip地址
	 * 
	 * @param context
	 * @return
	 */
	public static String getLocalIpAddress(Context context) {
		Enumeration<NetworkInterface> networkInterfaces = null;
		try {
			networkInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		if (networkInterfaces == null) {
			Log.i(tag, "cannot get  network interfaces");
			return null;
		}
		while (networkInterfaces.hasMoreElements()) {
			NetworkInterface networkInterface = networkInterfaces.nextElement();
			System.out.println(networkInterface.getName());
			for (Enumeration<InetAddress> enumIpAddr = networkInterface
					.getInetAddresses(); enumIpAddr.hasMoreElements();) {
				InetAddress inetAddress = enumIpAddr.nextElement();
				if (!inetAddress.isLoopbackAddress()) {
					return inetAddress.getHostAddress().toString();
				}
			}
		}

		return null;

	}

	public static String intToIpAddress(int address) {
		return (address & 0xFF) + "." + ((address >> 8) & 0xFF) + "."
				+ ((address >> 16) & 0xFF) + "." + (address >> 24 & 0xFF);
	}
}
